package com.jkj.http.sys.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpSession;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jkj.utils.JsonUtils;
import com.jkj.utils.OperatorProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.jkj.http.controller.BaseController;
import com.jkj.http.entity.LayPadding;
import com.jkj.http.entity.SysUserExt;
import com.jkj.http.interceptor.AuthorizeChecked;
import com.jkj.http.sys.entity.SysUser;
import com.jkj.http.sys.entity.SysUserLogOn;
import com.jkj.http.sys.entity.SysUserRoleRelation;
import com.jkj.http.sys.service.SysUserService;


@RestController
@RequestMapping(value = "/system/user")
public class UserController extends BaseController {
    @Autowired
    private SysUserService userService;

    /**
     * 用户列表页
     *
     * @return
     */
    @AuthorizeChecked()
    @RequestMapping(value = "/index", method = {RequestMethod.GET})
    public ModelAndView index() {
        return new ModelAndView("system/user/index");
    }


    /**
     * 获得用户列表分页
     *
     * @param pageIndex
     * @param pageSize
     * @param keyWord
     * @return
     */
    @AuthorizeChecked()
    @RequestMapping(value = "/index", method = {RequestMethod.POST}, produces = "application/json; charset=utf-8")
    public String index(int pageIndex, int pageSize, String keyWord) {
        int totalCount = userService.getTotalCount(keyWord);
        PageHelper.startPage(pageIndex, pageSize);//这行是重点，表示从pageNum页开始，每页pageSize条数据
        List<SysUser> list = userService.getList(keyWord);
        PageInfo<SysUser> pageInfo = new PageInfo<SysUser>(list);

        //List<SysUser> pageData = userService.getList((pageIndex - 1) * pageSize, pageSize, keyWord);
        List<SysUser> pageData = pageInfo.getList();
        LayPadding<SysUser> result = new LayPadding<SysUser>();
        result.setResult(true);
        result.setMsg("success");
        result.setList(pageData);
        result.setCount(totalCount);
        return JsonUtils.toJSON(result);
    }

    @AuthorizeChecked()
    @RequestMapping(value = "/form", method = {RequestMethod.GET})
    public ModelAndView form() {
        return new ModelAndView("system/user/form");
    }

    /**
     * 修改新增用户登录账号
     *
     * @param session
     * @param model
     * @param password
     * @param roleIds
     * @return
     */
    @AuthorizeChecked()
    @RequestMapping(value = "/form", method = {RequestMethod.POST}, produces = "application/json; charset=utf-8")
    public String form(HttpSession session, SysUser model, String password, String roleIds) {
        try {
            if (StrUtil.isEmpty(model.getId())) {
                model.setBirthday(DateUtil.parse(model.getStrBirthDay()));
                //新增用户基本信息。
                model.setCreateUser(OperatorProvider.getCurrent(session).getAccount());
                int n = userService.insert(model);
                if (n <= 0)
                    return error();
                //新增用户角色信息。
                userService.setRole(session, model.getId(), roleIds.split(","));
                //新增用户登陆信息。
                SysUserLogOn userLogOnEntity = new SysUserLogOn();
                userLogOnEntity.setUserId(model.getId());
                userLogOnEntity.setPassword(password);
                int userLoginId = userService.insertUserLogOn(userLogOnEntity);
                return userLoginId > 0 ? success() : error();
            } else {
                model.setBirthday(DateUtil.parse(model.getStrBirthDay()));
                //更新用户基本信息。
                model.setModifyUser(OperatorProvider.getCurrent(session).getAccount());
                int row = userService.update(model);
                //更新用户角色信息。
                userService.setRole(session, model.getId(), roleIds.split(","));
                return row > 0 ? success() : error();
            }
        } catch (Exception ex) {
            return error();
        }
    }

    /**
     * 用户信息详情页
     *
     * @return
     */
    @AuthorizeChecked()
    @RequestMapping(value = "/detail", method = {RequestMethod.GET})
    public ModelAndView detail() {
        return new ModelAndView("system/user/detail");
    }

    /**
     * 根据主键得到用户信息
     *
     * @param primaryKey
     * @return
     */
    @RequestMapping(value = "/getForm", method = {RequestMethod.POST}, produces = "application/json; charset=utf-8")
    public String getForm(String primaryKey) {
        SysUser entity = userService.get(primaryKey);
        entity.setStrBirthDay(DateUtil.format(entity.getBirthday(), "yyyy-MM-dd"));
        entity.setStrCreateTime(DateUtil.format(entity.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
        entity.setStrModifyTime(DateUtil.format(entity.getModifyTime(), "yyyy-MM-dd HH:mm:ss"));
        List<SysUserRoleRelation> roleRelationList = userService.getUserRoleList(entity.getId());
        List<String> roleId = new ArrayList<String>();
        for (SysUserRoleRelation item : roleRelationList) {
            roleId.add(item.getRoleId());
        }
        SysUserExt entityExt = new SysUserExt();
        entityExt.setAccount(entity.getAccount());
        entityExt.setAddress(entity.getAddress());
        entityExt.setAvatar(entity.getAvatar());
        entityExt.setBirthday(entity.getBirthday());
        entityExt.setCompanyId(entity.getCompanyId());
        entityExt.setCreateTime(entity.getCreateTime());
        entityExt.setCreateUser(entity.getCreateUser());
        entityExt.setDeleteMark(entity.getDeleteMark());
        entityExt.setDepartmentId(entity.getDepartmentId());
        entityExt.setDeptName(entity.getDeptName());
        entityExt.setEmail(entity.getEmail());
        entityExt.setGender(entity.getGender());
        entityExt.setId(entity.getId());
        entityExt.setIsEnabled(entity.getIsEnabled());
        entityExt.setMobilePhone(entity.getMobilePhone());
        entityExt.setModifyTime(entity.getModifyTime());
        entityExt.setModifyUser(entity.getModifyUser());
        entityExt.setNickName(entity.getNickName());
        entityExt.setRealName(entity.getRealName());
        entityExt.setSignature(entity.getSignature());
        entityExt.setSortCode(entity.getSortCode());
        entityExt.setStrBirthDay(entity.getStrBirthDay());
        entityExt.setRoleId(roleId);
        entityExt.setStrCreateTime(entity.getStrCreateTime());
        entityExt.setStrModifyTime(entity.getStrModifyTime());
        return JsonUtils.toJSON(entityExt);
    }

    /**
     * 删除用户信息
     */
    @AuthorizeChecked()
    @RequestMapping(value = "/delete", method = {RequestMethod.POST}, produces = "application/json; charset=utf-8")
    public String delete(String userIds) {
        //多用户删除。
        int row = userService.delete(userIds.split(","));
        userService.deleteUserRoleRelation(userIds.split(","));
        userService.deleteLogOnUser(userIds.split(","));
        return row > 0 ? success() : error();
    }

    /**
     * 根据账号得到用户信息
     *
     * @param userName
     * @return
     */
    @RequestMapping(value = "/checkAccount", method = {RequestMethod.POST}, produces = "application/json; charset=utf-8")
    public String checkAccount(String userName) {
        SysUser userEntity = userService.getByUserName(userName);
        if (userEntity != null) {
            return error("已存在当前用户名，请重新输入");
        }
        return success("恭喜您，该用户名可以注册");
    }
}
